package com.example.essayController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.example.essayRes.Essay;
import com.example.essayRes.User;

public class EssayController extends Controller{
	private DocumentBuilderFactory dbFactory;   
	private DocumentBuilder builder;
	//private HttpClient httpClient;

	public EssayController() {}
	
	public boolean init() {
		dbFactory = DocumentBuilderFactory.newInstance();  
		try {
			builder = dbFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public boolean findEssayByID(Essay essay) throws SAXException, IOException{
		Document document = builder.parse(siteUri + projectName + "essay/"+ essay.getID());
		NodeList nodeList = document.getElementsByTagName("essay");
		if (nodeList.getLength() > 0)
			return (nodeList.item(0).getChildNodes().getLength() > 0);
		else
			return false;
	}
	
	public boolean addEssay(User user, Essay essay) throws SAXException, IOException, TransformerException{
		// Could be more Strong, like checking response.getStatusLine()
		if (findEssayByID(essay)) return false;
		
		String essayID = essay.getTitle();
		
		//Step 1 : POST essay TABLE
		Document document = builder.newDocument();
		Element xmlEssay = document.createElement("user"), record = document.createElement("record"),
				summary = document.createElement("summary"),
				pKey = document.createElement("primaryKey"), title = document.createElement("title"),
				source = document.createElement("source"), body = document.createElement("body"),
				author = document.createElement("author"), submitDate = document.createElement("submitDate"),
				changeDate = document.createElement("changeDate"), status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		pKey.setTextContent(essayID);
		title.setTextContent(essay.getTitle());
		source.setTextContent(essay.getSource());
		body.setTextContent(essay.getBody());
		summary.setTextContent(essay.getSummary());
		// Here we don't need the name from essay, but from user
		author.setTextContent(user.getName());
		submitDate.setTextContent(essay.getSubmitDate());
		changeDate.setTextContent(essay.getChangeDate());
		// Here we don't need the status from essay
		status.setTextContent(Integer.toString(Essay.ESSAY_STATUS_EXAMINEFIRST));
		record.appendChild(pKey);
		record.appendChild(title);
		record.appendChild(source);
		record.appendChild(body);
		record.appendChild(author);
		record.appendChild(submitDate);
		record.appendChild(changeDate);
		record.appendChild(status);
		record.appendChild(summary);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);
		
		execHttpPost(document);
		
		// STEP 2: POST submit TABLE
		String userID = user.getID();
		document = builder.newDocument();
		record = document.createElement("record");
		Element xmlSubmit = document.createElement("submit"),
				dKey = document.createElement("domainkey"),
				rKey = document.createElement("rangekey"),
				comment = document.createElement("comment"),
				relation = document.createElement("relation");
		xmlSubmit.setAttribute("uri", projectName + "submit/"+ user.getID() + "@" + essayID);
		xmlSubmit.setAttribute("description", "submit");
		dKey.setTextContent(userID);
		rKey.setTextContent(essayID);
		comment.setTextContent("null");
		relation.setTextContent(Essay.COMMENT_STATUS_AUTHOR);
		record.appendChild(dKey);
		record.appendChild(rKey);
		record.appendChild(comment);
		record.appendChild(relation);
		xmlSubmit.appendChild(record);
		document.appendChild(xmlSubmit);
		execHttpPost(document);
		return true;
	}

	/**
	 * Change the status of Essay from DRAFT to EXAMINEFIRST
	 * Here especially for the revertEssay 
	 */
	public boolean submitEssay(User user, Essay essay) throws ClientProtocolException, IOException, TransformerException {
		if (essay.getStatus() != Essay.ESSAY_STATUS_DRAFT) return false;
		
		String essayID = essay.getID();
		Document document = builder.newDocument();
		Element xmlEssay = document.createElement("essay"), record = document.createElement("record"),
				status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		status.setTextContent(Integer.toString(Essay.ESSAY_STATUS_EXAMINEFIRST));
		record.appendChild(status);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);

		
		execHttpPut(document, siteUri + projectName + "essay/"+essayID);
		return true;
	}
	
	public boolean editEssay(User user, Essay newEssay, Essay oldEssay) throws ClientProtocolException, IOException, TransformerException {
		if (oldEssay.getStatus() == Essay.ESSAY_STATUS_RELEASED || oldEssay.getStatus() == Essay.ESSAY_STATUS_EXAMINEFINAL) return false;

		// newEssay may not have ID
		String essayID = oldEssay.getID();
		Document document = builder.newDocument();
		Element xmlEssay = document.createElement("essay"), record = document.createElement("record"),
				summary = document.createElement("summary"),
				pKey = document.createElement("primaryKey"),
				source = document.createElement("source"), body = document.createElement("body"),
				author = document.createElement("author"), submitDate = document.createElement("submitDate"),
				changeDate = document.createElement("changeDate"), status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		pKey.setTextContent(essayID);
		source.setTextContent(newEssay.getSource());
		body.setTextContent(newEssay.getBody());
		author.setTextContent(newEssay.getAuthor());
		summary.setTextContent(newEssay.getSummary());
		submitDate.setTextContent(oldEssay.getSubmitDate());
		changeDate.setTextContent((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
		status.setTextContent(Integer.toString(oldEssay.getStatus()));
		record.appendChild(pKey);
		record.appendChild(source);
		record.appendChild(body);
		record.appendChild(author);
		record.appendChild(summary);
		record.appendChild(submitDate);
		record.appendChild(changeDate);
		record.appendChild(status);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);
		
		execHttpPut(document, siteUri + projectName + "essay/"+essayID);
		return true;
	}
	
	public boolean deleteEssay(User user, Essay essay) throws SAXException, IOException {
		if (!findEssayByID(essay)) return false;
		if (essay.getStatus() != Essay.ESSAY_STATUS_DRAFT) return false;
		
		String essayID = essay.getID();
		// STEP 1: DELETE ESSAY
		execHttpDelete(siteUri + projectName + "essay/" + essayID);
		
		// STEP 2: DELETE all records in SUBMIT TABLE
		// There should be no commits for DRAFT essay
		/*Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			String deleteUri = eSubmit.getAttribute("uri");
			deleteUri = deleteUri.substring(projectName.length());
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				for (int j = 0; j < eMember.getLength(); j++) 
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						execHttpDelete(deleteUri);
						System.out.print(deleteUri);
					}
			}
		}*/
		return true;
	}
	
	public boolean revertEssay(User user, Essay essay) throws ClientProtocolException, IOException, TransformerException, SAXException {
		if (essay.getStatus() != Essay.ESSAY_STATUS_RELEASED) return false;
		
		// STEP 1: PUT essay TABLE
		String essayID = essay.getID();
		Document document = builder.newDocument();
		Element xmlEssay = document.createElement("user"), record = document.createElement("record"),
				status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		status.setTextContent(Integer.toString(Essay.ESSAY_STATUS_DRAFT));
		record.appendChild(status);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);
		
		execHttpPut(document, siteUri + projectName + "essay/"+essayID);
		
		//STEP 2: DELETE all comments in SUBMIT TABLE
		document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				boolean needDel = false;
				String userID = null;
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						needDel = true;
					}
					if ("domainkey".equals(eMember.item(j).getNodeName())) {
						userID = eMember.item(j).getFirstChild().getNodeValue(); 
					}
					if ("relation".equals(eMember.item(j).getNodeName()) &&
						Essay.COMMENT_STATUS_AUTHOR.equals(eMember.item(j).getFirstChild().getNodeValue())) { 
						needDel =false;
						break;
					}
				}
				if (needDel) {
					System.out.println(siteUri + projectName + "submit/" + userID + "@" + essayID);
					execHttpDelete(siteUri + projectName + "submit/" + userID + "@" + essayID);
				}
			}
			
		}
		return true;
	}
	
	/**
	 * For Author : It will return the list of his essays
	 * For Examinar : It will return the list of essays that he could examine
	 */
	public List<Essay> queryMyEssay(User user) throws SAXException, IOException {
		if (User.USER_TYPE_AUTHOR.equals(user.getType())) {
			String userID = user.getID();
			Document document = builder.parse(siteUri + projectName + "user/"+ userID);
			NodeList nodeList = document.getElementsByTagName("user");
			if (nodeList.getLength() > 0) {
				List<Essay> rtn = new ArrayList<Essay>();
				NodeList submitNode = nodeList.item(0).getChildNodes();
				for (int i = 0; i < submitNode.getLength(); i++) {
					Element eSubmit = (Element) submitNode.item(i);
					if ("submit".equals(eSubmit.getNodeName())) {
						NodeList essayNode = eSubmit.getChildNodes();
						for (int j = 0; j < essayNode.getLength(); j++) 
							if ("essay".equals(essayNode.item(j).getNodeName())){
								Element eleEssay = (Element) essayNode.item(j);
								rtn.add(Essay.xmlToEssay(eleEssay));
							}
					}
				}
				return rtn;
			}
			return null;
		}
		else {
			List<Essay> rtn = new ArrayList<Essay>();
			Document document = builder.parse(siteUri + projectName + "essay/*");
			Element root = document.getDocumentElement();
			NodeList nodeList = root.getElementsByTagName("essay");
			if (nodeList.getLength() > 0) {
				for (int i = 0; i < nodeList.getLength(); i++) {
					Element essEle = (Element) nodeList.item(i);
					Essay ess = Essay.xmlToEssay(essEle);
					if (ess.getStatus() != Essay.ESSAY_STATUS_DRAFT && ess.getStatus() != Essay.ESSAY_STATUS_RELEASED) {
						rtn.add(ess);
					}
				}
			}
			return rtn;
		}
	}
	
	/**
	 * the comment of specified essay & examinar
	 * @param user For examinar only
	 * @param essay
	 * @return 
	 * @throws SAXException
	 * @throws IOException
	 */
	public String getMyCommentForEssay(User user, Essay essay) throws SAXException, IOException {
		if (User.USER_TYPE_AUTHOR.equals(user.getType())) return null;
		String userID = user.getID(), essayID = essay.getID();
		
		// Check all records in SUBMIT TABLE
		Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				int alreadyHas = -2;
				String comment = "";
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						alreadyHas++; 
					}
					if ("domainkey".equals(eMember.item(j).getNodeName()) && 
						userID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						alreadyHas++; 
					}
					if ("comment".equals(eMember.item(j).getNodeName())) {
						comment = eMember.item(j).getFirstChild().getNodeValue(); 
					}
				}
				if (alreadyHas >= 0) return comment;
			}
			
		}
		return null;
	}
	
	private String getStatusOfMyCommentForEssay(User user, Essay essay) throws SAXException, IOException {
		if (User.USER_TYPE_AUTHOR.equals(user.getType())) return null;
		String userID = user.getID(), essayID = essay.getID();
		
		// Check all records in SUBMIT TABLE
		Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				int alreadyHas = -2;
				String status = "";
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						alreadyHas++; 
					}
					if ("domainkey".equals(eMember.item(j).getNodeName()) && 
						userID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						alreadyHas++; 
					}
					if ("relation".equals(eMember.item(j).getNodeName())) {
						status = eMember.item(j).getFirstChild().getNodeValue(); 
					}
				}
				if (alreadyHas >= 0) return status;
			}
			
		}
		return null;
	}

	/**
	 * Check whether the essay is being examined
	 * @param essay
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 */
	private boolean isExaminingEssay(Essay essay) throws SAXException, IOException {
		String essayID = essay.getID();
		
		// Check all records in SUBMIT TABLE
		Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				boolean thisEssay = false;
				String status = "";
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						thisEssay =true; 
					}
					if ("relation".equals(eMember.item(j).getNodeName())) {
						status = eMember.item(j).getFirstChild().getNodeValue(); 
					}
				}
				if (thisEssay && status.equals(Essay.COMMENT_STATUS_EXAMINING)) return false;
			}
			
		}
		return true;
	}
	
	public boolean addCommentToEssay(User user, Essay essay, String userComment) throws ClientProtocolException, TransformerException, IOException, SAXException {
		if (!User.USER_TYPE_EXAMINER.equals(user.getType())) return false;
		if (getMyCommentForEssay(user, essay) != null) return false;
		if (!isExaminingEssay(essay)) return false;
		if (essay.getStatus() == Essay.ESSAY_STATUS_EXAMINEULTI) return false;
		
		// POST submit TABLE
		String userID = user.getID(), essayID = essay.getID();
		Document document = builder.newDocument();
		Element xmlSubmit = document.createElement("submit"),
				record = document.createElement("record"),
				dKey = document.createElement("domainkey"),
				rKey = document.createElement("rangekey"),
				comment = document.createElement("comment"),
				relation = document.createElement("relation");
		xmlSubmit.setAttribute("uri", projectName + "submit/"+ userID + "@" + essayID);
		xmlSubmit.setAttribute("description", "submit");
		dKey.setTextContent(userID);
		rKey.setTextContent(essayID);
		comment.setTextContent(userComment);
		relation.setTextContent(Essay.COMMENT_STATUS_EXAMINING);
		record.appendChild(dKey);
		record.appendChild(rKey);
		record.appendChild(comment);
		record.appendChild(relation);
		xmlSubmit.appendChild(record);
		document.appendChild(xmlSubmit);
		//execHttpPost(document, siteUri + projectName + "submit/"+ userID + "@" + essayID);
		execHttpPost(document);
		return true;
	}
	
	public boolean editEssayComment(User user, Essay essay, String userComment) throws ClientProtocolException, IOException, TransformerException, SAXException {
		if (!User.USER_TYPE_EXAMINER.equals(user.getType())) return false;
		
		// PUT submit TABLE
		String userID = user.getID(), essayID = essay.getID();
		Document document = builder.newDocument();
		Element xmlSubmit = document.createElement("submit"),
				record = document.createElement("record"),
				//dKey = document.createElement("domainkey"),
				//rKey = document.createElement("rangekey"),
				comment = document.createElement("comment");
				//relation = document.createElement("relation");
		xmlSubmit.setAttribute("uri", projectName + "submit/"+ userID + "@" + essayID);
		xmlSubmit.setAttribute("description", "submit");
		//dKey.setTextContent(userID);
		//rKey.setTextContent(essayID);
		comment.setTextContent(userComment);
		//relation.setTextContent();
		//record.appendChild(dKey);
		//record.appendChild(rKey);
		record.appendChild(comment);
		//record.appendChild(relation);
		xmlSubmit.appendChild(record);
		document.appendChild(xmlSubmit);
		//execHttpPost(document, siteUri + projectName + "submit/"+ userID + "@" + essayID);
		execHttpPut(document, siteUri + projectName + "submit/"+ userID + "@" + essayID);
		return true;
	}
	
	/**
	 * Submit my comment of this essay
	 * @param user
	 * @param essay
	 * @param userComment
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws TransformerException
	 * @throws SAXException
	 */
	public boolean submitEssayComment(User user, Essay essay, String userComment) throws ClientProtocolException, IOException, TransformerException, SAXException {
		if (!Essay.COMMENT_STATUS_EXAMINING.equals(getStatusOfMyCommentForEssay(user, essay))) return false;
		if (!editEssayComment(user, essay ,userComment)) return false;
		
		String userID = user.getID(), essayID = essay.getID();
		int essNextStatus = Essay.nextStatus(essay.getStatus());
		// STEP 1 : PUT submit TABLE
		Document document = builder.newDocument();
		Element xmlSubmit = document.createElement("submit"),
				record = document.createElement("record"),
				//dKey = document.createElement("domainkey"),
				//rKey = document.createElement("rangekey"),
				relation = document.createElement("relation");
		xmlSubmit.setAttribute("uri", projectName + "submit/"+ userID + "@" + essayID);
		xmlSubmit.setAttribute("description", "submit");
		//dKey.setTextContent(userID);
		//rKey.setTextContent(essayID);
		//comment.setTextContent(userComment);
		relation.setTextContent(Essay.getStatusOfSubmmitedComment(essNextStatus));
		//record.appendChild(dKey);
		//record.appendChild(rKey);
		//record.appendChild(comment);
		record.appendChild(relation);
		xmlSubmit.appendChild(record);
		document.appendChild(xmlSubmit);
		execHttpPut(document, siteUri + projectName + "submit/"+ userID + "@" + essayID);
		
		// STEP 2 : PUT essay TABLE
		document = builder.newDocument();
		record = document.createElement("record");
		Element xmlEssay = document.createElement("user"),
				status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		status.setTextContent(Integer.toString(essNextStatus));
		record.appendChild(status);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);

		execHttpPut(document, siteUri + projectName + "essay/"+essayID);
		return true;
	}
	
	/**
	 * Submit my comment of this essay and give it pass or not
	 * @param user
	 * @param essay
	 * @param userComment
	 * @param pass
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws TransformerException
	 * @throws SAXException
	 */
	public boolean submitEssayComment(User user, Essay essay, String userComment, Boolean pass) throws ClientProtocolException, IOException, TransformerException, SAXException {
		if (submitEssayComment(user, essay, userComment))
			if (approveEssay(user, essay, pass))
				return true;
		return false;
	}
	
	private boolean approveEssay(User user, Essay essay, Boolean pass) throws ClientProtocolException, IOException, TransformerException, SAXException {
		// Here essay is old and its status has not been updated but COMMENT STATUS has been updated
		if (essay.getStatus() != Essay.ESSAY_STATUS_EXAMINEFINAL) return false;
		
		if (!Essay.COMMENT_STATUS_SUBMITTEDULTI.equals(getStatusOfMyCommentForEssay(user, essay))) return false;
		
		String essayID = essay.getID();
		Document document = builder.newDocument();
		Element xmlEssay = document.createElement("user"), record = document.createElement("record"),
				status = document.createElement("status");
		xmlEssay.setAttribute("uri", projectName + "essay/"+essayID);
		xmlEssay.setAttribute("description", "essay");
		if (pass)
			status.setTextContent(Integer.toString(Essay.ESSAY_STATUS_RELEASED));
		else
			status.setTextContent(Integer.toString(Essay.ESSAY_STATUS_DRAFT));
		record.appendChild(status);
		xmlEssay.appendChild(record);
		document.appendChild(xmlEssay);
		
		execHttpPut(document, siteUri + projectName + "essay/"+essayID);
		// DELETE all comments in SUBMIT TABLE
		if (!pass) {
			document = builder.parse(siteUri + projectName + "submit/*");
			Element root = document.getDocumentElement();
			NodeList nodeList = root.getElementsByTagName("submit");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Element eSubmit = (Element) nodeList.item(i);
				NodeList rec = eSubmit.getChildNodes();
				if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
					NodeList eMember = rec.item(0).getChildNodes();
					boolean needDel = false;
					String userID = null;
					for (int j = 0; j < eMember.getLength(); j++) {
						if ("rangekey".equals(eMember.item(j).getNodeName()) && 
							essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
							needDel = true;
						}
						if ("domainkey".equals(eMember.item(j).getNodeName())) {
							userID = eMember.item(j).getFirstChild().getNodeValue(); 
						}
						if ("relation".equals(eMember.item(j).getNodeName()) &&
							Essay.COMMENT_STATUS_AUTHOR.equals(eMember.item(j).getFirstChild().getNodeValue())) { 
							needDel =false;
							break;
						}
					}
					if (needDel) {
						System.out.println(siteUri + projectName + "submit/" + userID + "@" + essayID);
						execHttpDelete(siteUri + projectName + "submit/" + userID + "@" + essayID);
					}
				}
				
			}
		}
		return true;
	}
	
	/**
	 * Get comments of specified author & essay
	 * @param user Only for Author User
	 * @param essay
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 */
	public List<String> getMyEssayComments(User user, Essay essay) throws SAXException, IOException {
		if (!ifMyEssay(user, essay)) return null;
		
		List<Essay> essayList = queryMyEssay(user);
		if (!essayList.contains(essay)) return null;
		return getEssayComments(essay);
	}
	
	/**
	 * Usually for examiners get comments of the specified essay 
	 * @param essay
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 */
	public List<String> getEssayComments(Essay essay) throws SAXException, IOException {
		// Only SUBMIT STATUS is COMMENT_STATUS_SUBMITTED, then you can see it
		String essayID = essay.getID();
		
		List<String> rtn = new ArrayList<String>();
		
		// Check all records in SUBMIT TABLE
		Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				boolean needThisComment = false;
				String comment = "";
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName()) && 
						essayID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						needThisComment = true;
					}
					if ("comment".equals(eMember.item(j).getNodeName())) {
						comment = eMember.item(j).getFirstChild().getNodeValue(); 
					}
					if ("relation".equals(eMember.item(j).getNodeName()) && 
						(Essay.COMMENT_STATUS_EXAMINING.equals(eMember.item(j).getFirstChild().getNodeValue()) ||
						Essay.COMMENT_STATUS_AUTHOR.equals(eMember.item(j).getFirstChild().getNodeValue()))) {
						needThisComment = false;
						break;
					}
				}
				if (needThisComment) rtn.add(comment);
			}
			
		}
		return rtn;
	}

	/**
	 * Search essays must by some conditions
	 * @param queryMap
	 * @param fuzzy
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 */
	public List<Essay> queryEssay(Map<String, String> queryMap, Boolean fuzzy) throws SAXException, IOException{
		StringBuilder query = new StringBuilder();
		if (queryMap == null) return getAllReleasedEssays();
		for (String qKey : queryMap.keySet()) {
			String qValue = queryMap.get(qKey);
			query.append(qKey);
			query.append("=");
			query.append(qValue);
			query.append("&");
		}
		if (fuzzy)
			query.append("fuzzy=1");
		else
			query.deleteCharAt(query.length()-1);
		//System.out.println(query.toString());
		
		List<Essay> rtn = new ArrayList<Essay>();
		Document document = builder.parse(siteUri + projectName + "essay/?" + query.toString());
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("essay");
		if (nodeList.getLength() > 0) {
			for (int i = 0; i < nodeList.getLength(); i++) {
				Element essEle = (Element) nodeList.item(i);
				Essay essay = Essay.xmlToEssay(essEle); 
				if (essay.getStatus() == Essay.ESSAY_STATUS_RELEASED)
					rtn.add(essay);
			}
		}
		return rtn;
	}
	
	/**
	 * 
	 * @param user For examinar only
	 * @return
	 * @throws SAXException
	 * @throws IOException
	 */
	public List<Essay> queryMyCommentingEssay(User user) throws SAXException, IOException {
		List<Essay> rtn = new ArrayList<Essay>();
		String userID = user.getID();
		
		// Check all records in SUBMIT TABLE
		Document document = builder.parse(siteUri + projectName + "submit/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("submit");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element eSubmit = (Element) nodeList.item(i);
			NodeList rec = eSubmit.getChildNodes();
			if (rec.getLength() > 0 && rec.item(0).getNodeName().equals("record")) {
				NodeList eMember = rec.item(0).getChildNodes();
				boolean needThis = false;
				String essayID = null;
				for (int j = 0; j < eMember.getLength(); j++) {
					if ("rangekey".equals(eMember.item(j).getNodeName())) {
						essayID = eMember.item(j).getFirstChild().getNodeValue();
					}
					if ("domainkey".equals(eMember.item(j).getNodeName()) && 
						userID.equals(eMember.item(j).getFirstChild().getNodeValue())) {
						needThis = true;
					}
					if ("relation".equals(eMember.item(j).getNodeName()) && 
						(Essay.COMMENT_STATUS_EXAMINING.equals(eMember.item(j).getFirstChild().getNodeValue()))) {
						needThis = false;
						break;
					}
				}
				if (needThis) rtn.add(getEssay(essayID));
			}
			
		}
		return null;
	}
	
	private Essay getEssay(String essayID) throws SAXException, IOException {
		Document document = builder.parse(siteUri + projectName + "essay/"+ essayID);
		NodeList nodeList = document.getElementsByTagName("essay");
		return Essay.xmlToEssay((Element) nodeList.item(0));
	}
	
	private boolean ifMyEssay(User user, Essay essay) {
		return true;
	}
	
	public List<Essay> getAllReleasedEssays() throws SAXException, IOException {
		List<Essay> rtn = new ArrayList<Essay>();
		Document document = builder.parse(siteUri + projectName + "essay/*");
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("essay");
		if (nodeList.getLength() > 0) {
			for (int i = 0; i < nodeList.getLength(); i++) {
				Element essEle = (Element) nodeList.item(i);
				Essay essay = Essay.xmlToEssay(essEle); 
				if (essay.getStatus() == Essay.ESSAY_STATUS_RELEASED)
					rtn.add(essay);
			}
		}
		return rtn;
	}
}
